<template>
  <div v-if="isReload">
    <card :isCustomHeader="true">
      <template #header>
        <t-breadcrumb :maxItemWidth="'150'">
          <t-breadcrumbItem>企业管理</t-breadcrumbItem>
          <t-breadcrumbItem><b>用户</b></t-breadcrumbItem>
        </t-breadcrumb>
        <t-button @click="$router.push('/business-management/user/addUser')">添加用户</t-button>
      </template>
      <template>
        <t-space direction="vertical" style="width: 100%">
          <t-row>
            <t-col :span="2">
              <div class="box">
                <t-space :size="8">
                  <t-button
                    variant="outline"
                    :disabled="selectedRowKeys.length === 0"
                    theme="primary"
                    @click="changeState"
                    >更改状态</t-button
                  >
                  <t-button
                    @click="handleDeleteRow"
                    variant="outline"
                    theme="danger"
                    :disabled="selectedRowKeys.length === 0"
                    >批量删除</t-button
                  >
                </t-space>
              </div>
            </t-col>
            <t-col :span="2" :offset="8">
              <t-input autofocus style="width: 90%" clearable @change="search">
                <search-icon slot="prefix-icon"></search-icon>
              </t-input>
            </t-col>
          </t-row>
        </t-space>
        <t-table
          rowKey="id"
          :data="data"
          :columns="columns"
          :sort="sort"
          @sort-change="sortChange"
          :showSortColumnBgColor="true"
          :filter-value="filterValue"
          @filter-change="onFilterChange"
          :hover="hover"
          :size="size"
          :filterRow="() => null"
          :table-layout="tableLayout ? 'auto' : 'fixed'"
          :showHeader="showHeader"
          @select-change="rehandleSelectChange"
          cellEmptyContent="-"
        >
          <template #name="{ row }">
            <p class="name">{{ row.name }}</p>
          </template>

          <template #status="{ row }">
            <t-tag v-if="row.status == '2'" variant="outline" theme="danger" class="danger">已禁用</t-tag>
            <t-tag v-else variant="outline" theme="success" class="success">使用中</t-tag>
          </template>

          <template #mobile="{ row }">
            <mobile-icon class="mobile" /><span>{{ row.mobile }}</span>
          </template>
          <template #email="{ row }">
            <mail-icon /> <span>{{ row.email }}</span>
          </template>
        </t-table>
        <t-pagination
          v-model="pagination.defaultCurrent"
          @change="pageChange"
          :total="pagination.total"
          :page-size.sync="pagination.defaultPageSize"
          show-jumper
          style="margin-top: 20px"
        />
      </template>
    </card>
  </div>
</template>

<script lang="jsx">
import Card from '@/components/Card/index.vue';
import { mapState } from 'vuex';
import { SearchIcon, DeleteIcon, EditIcon, MailIcon, MobileIcon } from 'tdesign-icons-vue';
import { DialogPlugin } from 'tdesign-vue';
import { deleteUser, changeState } from '@/service/business-management/users/index';
import { debounce } from '@/utils';

export default {
  name: 'BusinessManagementRegister',
  components: {
    Card,
    SearchIcon,
    MailIcon,
    MobileIcon,
  },
  data() {
    return {
      isReload: true,
      selectedRowKeys: [],
      userStatusList: [],
      total: 0,
      data: [],
      filterValue: {
        createTime: [],
      },
      // 操作的关键词 筛选，排序
      oprationkW: {},
      size: 'medium',
      tableLayout: false,
      hover: true,
      showHeader: true,
      // 排序
      sort: {
        // 按照 status 字段进行排序
        sortBy: 'ID',
        // 是否按照降序进行排序
        descending: false,
      },
      columns: [
        {
          colKey: 'row-select',
          type: 'multiple',
          className: 'demo-multiple-select-cell',
        },
        {
          colKey: 'name',
          title: '用户名称',
          // ellipsis: true,
        },
        {
          colKey: 'status',
          title: '账户状态',
          sorter: true,
          // 多选过滤配置
          filter: {
            type: 'multiple',
            resetValue: [],
            // 是否显示重置取消按钮，一般情况不需要显示
            showConfirmAndReset: true,
            list: [
              { label: '已禁用', value: '0' },
              { label: '使用中', value: '1' },
            ],
          },
        },
        {
          colKey: 'role',
          title: '角色',
          sorter: true,
          ellipsis: true,
          ellipsisTitle: false,
          // 多选过滤配置
          filter: {
            type: 'multiple',
            resetValue: [],
            // 是否显示重置取消按钮，一般情况不需要显示
            showConfirmAndReset: true,
            list: [
              { label: '待处置', value: '2' },
              { label: '待审核', value: '3' },
              { label: '已完成', value: '4' },
            ],
          },
        },
        {
          colKey: 'orgName',
          title: '所属企业',
          ellipsis: true,
        },
        {
          colKey: 'mobile',
          title: '手机号码',
          // width: 240,
          ellipsis: true,
        },
        {
          colKey: 'email',
          title: '邮箱',
          // width: 250,
          ellipsis: true,
        },
        {
          colKey: 'creatorName',
          title: '创建人',
          // width: 200,
          ellipsis: true,
          ellipsisTitle: false,
          sortType: 'all',
          sorter: true,
        },
        {
          colKey: 'action',
          title: '操作',
          width: 200,
          // 增、删、改、查 等操作
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          cell: (h, { row }) => (
            <div class="tdesign-table-demo__table-operations">
              <t-button variant="text" onClick={() => this.edit(row)}>
                <EditIcon></EditIcon>
              </t-button>
              <t-button variant="text" onClick={() => this.deleteRow(row)}>
                <DeleteIcon></DeleteIcon>
              </t-button>
            </div>
          ),
        },
      ],
      // 分页器
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        total: 0,
      },
    };
  },
  computed: {
    ...mapState('businessRole', ['userInfo']),
    userId() {
      return this.$store.state.user.userInfo.id;
    },
  },
  mounted() {
    this.getUserInfo();
  },
  methods: {
    reload() {
      this.isReload = false;
      this.$nextTick(() => {
        this.isReload = true;
      });
    },
    async getUserInfo() {
      const pageSize = this.pagination.defaultPageSize;
      const pageNum = this.pagination.defaultCurrent;
      const roleDTO = { pageNum, pageSize, ...this.oprationkW };

      await this.$store.dispatch('businessRole/requireAllUserInfo', roleDTO);

      this.data = this.userInfo.allUserVO.list;
      // this.columns[3].filter.list=
      this.pagination.total = this.userInfo?.allUserVO.total;

      // 渲染筛选框选项内容
      const roleSet = this.userInfo.userRoleSet.map((item) => item.role);
      this.columns[3].filter.list = roleSet;
    },
    // 输入框搜索
    search: debounce(function fn(value) {
      const inputContent = value;
      this.oprationkW = { ...this.oprationkW, inputContent };

      // 如果没有搜索参数value，接口要求也不传key
      if (!value) this.$delete(this.oprationkW, 'value');
      this.pagination.defaultCurrent = 1;
      this.getUserInfo();
    }, 1000),
    // 排序
    sortChange(sort) {
      this.sort = sort;
      this.sortRequest(sort);
    },
    sortRequest(sort) {
      // 不排序的时候 不传参数
      if (!sort) {
        this.$delete(this.oprationkW, 'orderColum');
        this.$delete(this.oprationkW, 'orderType');
        this.getUserInfo();
        return;
      }
      let orderColum;
      let orderType;
      orderType = 'desc';
      if (sort?.descending) orderType = 'asc';
      orderColum = 'status';
      if (sort?.sortBy === 'role') orderColum = 'role';
      if (sort?.sortBy === 'creatorName') orderColum = 'creatorName';

      // 如果过滤也同时存在
      if (this.oprationkW.roleNameList) {
        this.oprationkW = { ...this.oprationkW, orderColum, orderType };
        this.sortRequest();
        return;
      }

      // 只有排序的时候
      this.oprationkW = { ...this.oprationkW, orderColum, orderType };
      this.getUserInfo();
    },
    // 过滤
    onFilterChange(filters) {
      this.filterValue = {
        ...filters,
        createTime: filters.createTime || [],
      };
      this.filterRequest(this.filterValue);
    },
    filterRequest(filters) {
      const roleList = [];
      // eslint-disable-next-line array-callback-return
      filters.role.map((item) => {
        const id = this.userInfo.userRoleSet.forEach((val) => {
          if (item === val.role) {
            roleList.push(val.roleId);
          }
        });
        return id;
      });
      const statusList = filters.status;
      this.oprationkW = { ...this.oprationkW, roleList, statusList };

      // 如果没有过滤参数value，接口要求也不传key
      if (!roleList || roleList?.length === 0) this.$delete(this.oprationkW, 'roleList');
      if (!statusList || statusList?.length === 0) this.$delete(this.oprationkW, 'statusList');
      this.pagination.defaultCurrent = 1;
      this.getUserInfo();
    },
    pageChange({ current, pageSize }) {
      this.pagination.defaultCurrent = current;
      this.pagination.defaultPageSize = pageSize;
      this.getUserInfo(current, pageSize);
    },
    rehandleSelectChange(val, row) {
      this.selectedRowKeys = val;
      if (row.selectedRowData.length > 0) {
        this.userStatusList = row.selectedRowData.map((item) => ({
          id: item.id,
          status: item.status,
        }));
      }
    },
    deleteRow(row) {
      this.deleteData([row.id]);
    },
    handleDeleteRow() {
      this.deleteData(this.selectedRowKeys);
    },
    deleteData(ids) {
      const dialog = DialogPlugin.confirm({
        theme: 'warning',
        header: '提示',
        body: '再次确认是否删除？',
        onConfirm: () => {
          if (ids.includes(this.userId)) {
            this.$message.warning('不能删除自己的用户');
            return;
          }
          deleteUser(ids).then((res) => {
            if (!res || res.isError) return;
            this.selectedRowKeys = [];
            this.$message.success('删除成功');
            this.getUserInfo();
            this.reload();
            dialog.destroy();
          });
        },
      });
    },
    edit(row) {
      this.$router.push({
        path: '/business-management/user/editUser',
        query: { id: row.id },
      });
    },
    changeState() {
      const dialog = DialogPlugin.confirm({
        theme: 'warning',
        header: '提示',
        body: '再次确认是否更改状态？',
        onConfirm: () => {
          changeState(this.userStatusList).then((res) => {
            if (!res || res.isError) return;
            this.$message.success('更改状态成功');
            this.selectedRowKeys = [];
            this.reload();
            this.getUserInfo();
            dialog.destroy();
          });
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.name {
  color: #0052d9;
}
.success {
  background-color: #e8f8f2;
}
.danger {
  background-color: #fdecee;
}
.mobile {
  margin-bottom: 3px;
}
</style>
